package foo.bar.wiki.web.action.resource;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.web.action.page.PageActionBean;
import foo.bar.wiki.web.extension.ResourceTypeConverter;
import foo.bar.wiki.web.extension.PageTypeConverter;
import foo.bar.wiki.services.WikiService;
import foo.bar.wiki.services.exception.BusinessLogicExecution;
import foo.bar.wiki.domain.Resource;
import foo.bar.wiki.domain.Page;
import foo.bar.wiki.utils.IOUtils;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;

import java.io.IOException;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class AddResourceActionBean extends BaseActionBean {

    public static final String VIEW = "/resource/addResource.jsp";

    private WikiService wikiService;

    @Validate(required = true, on={"save"})
    private FileBean file;


    @Validate(converter = PageTypeConverter.class)
    private Page page;

    @Validate(converter = ResourceTypeConverter.class)
    private Resource resource;


    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution(generateThemePath(VIEW));
    }


    public Resolution save() throws Throwable {
        return handleBusinessLogicException(new BusinessLogicExecution(){
            public Resolution execute() throws Throwable {
                resource = wikiService.saveResource(resource);
                resource.setMimeType(file.getContentType());
                resource.setContent(IOUtils.toBytes(file.getInputStream()));
                resource.setPage(page);
                page.getResources().add(resource);
                resource = (Resource) wikiService.saveOrUpdate(resource);

                getContext().getMessages().add(new SimpleMessage("Resource ["+resource.getName()+"] saved successfully"));
                return new RedirectResolution(PageActionBean.class, "view").addParameter("page", page.getId()).addParameter("tab", "3");
            }
        });
    }




    @SpringBean("wikiService")
    public void setWikiService(WikiService wikiService) {
        this.wikiService = wikiService;    
    }


    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    public FileBean getFile() {
        return file;
    }

    public void setFile(FileBean file) {
        this.file = file;
    }
}
